package lib

import (
	"GameServer/Common/data"
	"GameServer/Common/utils"
	"GameServer/Game/dbmodule"
	"GameServer/Game/m"
	"fmt"

	"github.com/globalsign/mgo/bson"
)

func GetActRankByGroupId(groupId int64) (r *m.ActRankGroup) {
	arm := m.GetActRankGroupByGroupId(groupId)
	return arm
}

func AddItemToActRank(u *m.User, addNum int64, actId int64, rankRewardId int64, orgItemNum int64) (rankId int64) {
	arm := m.GetActRankGroupByGroupId(u.UserGroup)
	if arm != nil {
		rankId = arm.AddItem(u.Uid.Hex(), addNum)
	} else {
		nowUnix := utils.TNow().Unix()
		offLine7DayUnix := nowUnix - 86400*7
		// 找出7天未登录过的玩家
		noUsers := make([]*m.User, 0)
		dbmodule.MgoDB.GameDB.FindAll("user", bson.M{"last_login_time": bson.M{"$lt": offLine7DayUnix}}, nil, &noUsers)
		// 保证数组里面至少40个用户，防止填充失败
		for noLen := len(noUsers); noLen < 40; noLen++ {
			noUsers = append(noUsers, &m.User{
				Name:        fmt.Sprintf("%s", utils.GenName()),
				Head:        fmt.Sprintf("%s", utils.GenDefaultHead()),
				AvatarFrame: data.AvatarFrameEnum.DefaultFrame,
			})
		}

		arm := u.CreateActRankGroup(actId, rankRewardId)
		u.ChangeUserGroup(arm.GroupId)
		arm.AddMember(&m.UserActRank{
			Uid:         u.Uid.Hex(),
			Name:        u.Name,
			Head:        u.Head,
			AvatarFrame: u.AvatarFrame,
			Item:        orgItemNum,
			LastRankId:  0,
			RankId:      0,
			IsRobot:     1,
		})
		// actTurn, offsetTime := GetActTurn(actId)
		offsetTime := nowUnix - utils.ZeroTime(utils.TNow())
		arm.TryFillUpMemberWithRobot(1, offsetTime, noUsers[:39])
		arm.AddItem(u.Uid.Hex(), addNum)
		rankId = arm.ReSort(u.Uid.Hex())
	}
	return
}
